/*
 * @Author: yangzonglong
 * @Date: 2021-05-07 14:05:05
 * @version: v1.0.0
 * @Descripttion: 表单设计
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-06 15:22:57
 * @Auditor:
 */
import React, { useRef, forwardRef, useImperativeHandle, useCallback, useEffect, useMemo } from 'react';
import { Design } from './../fd';
import { DesignRefProps, ControlProps } from './../fd/interface';

const LFORM = '/fd/form_design_extra';
interface FormDesignProps {
  formEngine: 'LFORM' | 'GFORM' | string;
  onOk(data: string): void;
  content?: string;
  formInfo?: { formDesc?: string; formName?: string };
  onChange?(data: any): void; // 表单设计变化时触发回调 目前只支持gform
}
export interface FormDesignRefProps {
  getDesign(formName: string, next?: Function, isExport?: boolean): any;
  preview(): void;
  syncGform(list: ControlProps[]): void;
}

export default forwardRef(({ formEngine, onOk, content, onChange, formInfo }: FormDesignProps, ref: React.Ref<FormDesignRefProps>) => {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const fdRef = useRef<DesignRefProps>(null);
  useImperativeHandle(ref, () => ({
    preview() {
      fdRef.current?.changePreview();
      fdRef.current?.setFormInfo(formInfo!);
    },
    getDesign(formName, next?: Function, isExport?: boolean) {
      if (formEngine === 'LFORM') {
        iframeRef.current?.contentWindow?.postMessage(
          {
            action: 'saveTemplate',
            data: { formName },
          },
          '*'
        );
      } else if (formEngine === 'GFORM') {
        const data = fdRef.current?.getData(isExport);
        if (next) return next(JSON.stringify(data));
        onOk(JSON.stringify(data));
      }
    },
    syncGform(list: ControlProps[]) {
      fdRef.current?.sync(list);
    },
  }));

  const receiveMessage = useCallback(
    (event: any) => {
      const data = event.data;
      if (data && data.action === 'saveTemplate') {
        onOk && onOk(data.content);
      }
    },
    [onOk]
  );

  useEffect(() => {
    window.addEventListener('message', receiveMessage, false);
    return () => {
      window.removeEventListener('message', receiveMessage);
    };
  }, [receiveMessage]);

  const onLoad = useCallback(() => {
    iframeRef.current?.contentWindow?.postMessage(
      {
        action: 'editTemplate',
        templateDef: content,
      },
      '*'
    );
  }, [content]);

  const formContent = useMemo(() => {
    if (!content || formEngine === 'LFORM') return {};
    try {
      return JSON.parse(content);
    } catch (error) {
      console.log(error, '解决content格式出错');
      return {};
    }
  }, [content, formEngine]);

  return formEngine === 'LFORM' ? (
    <iframe onLoad={onLoad} src={LFORM} ref={iframeRef} width="100%" height="100%" title="LFORM" frameBorder="0" />
  ) : (
    <Design onChange={onChange} structure={formContent} noFormNameDesc ref={fdRef} />
  );
});
